package cn.tedu.bonfire.front.payment.service.impl;

import cn.tedu.bonfire.front.payment.config.AliPayConfig;
import cn.tedu.bonfire.front.payment.dao.persist.repository.IPayRepository;
import cn.tedu.bonfire.front.payment.pojo.entity.AliPayBean;
import cn.tedu.bonfire.front.payment.pojo.param.AliPayParam;
import cn.tedu.bonfire.front.payment.pojo.param.OrderParam;
import cn.tedu.bonfire.front.payment.service.IOrderService;
import cn.tedu.bonfire.front.payment.service.IPayModelService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

@Service
public class PayModelServiceImpl implements IPayModelService {

    @Autowired
    private AliPayConfig alipayConfig;

    @Autowired
    private IPayRepository repository;

    @Autowired
    private IOrderService orderService;

    @Override
    public String aliPay(Long userId, AliPayParam aliPayParam) throws AlipayApiException, IOException {
        String outTradeNo;
        Long count = 0L;
        do {
            outTradeNo = CreateOutTradeNoRandom(userId);
            count = orderService.countByOutTradeNo(outTradeNo);
        } while (count < 0);

        /* 生成订单 */
        OrderParam orderDto = new OrderParam();
        orderDto.setOrderNo(outTradeNo);
        orderDto.setTotalPrice(aliPayParam.getMoney());
        orderDto.setBuyerId(userId);
        orderDto.setOrderState(0);
        orderService.createOrder(orderDto);

        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject("正在充值");
        alipayBean.setTotal_amount(aliPayParam.getMoney());
        alipayBean.setBody("感谢");
        String aliPay = repository.aliPay(alipayBean);
        return aliPay;
    }

    @Override
    public void updateOrderStatus(String outTradeNo) {

        orderService.updateOrderStatus(outTradeNo);

    }

    /**
     * 验证签名方法
     * @param params
     * @return
     * @throws AlipayApiException
     */
    @Override
    public boolean aliSignature(Map<String, String> params) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
        if (!signVerified) {
            return false;
        }
        return true;
    }

    /**
     * 生成随机订单号
     * @param id
     * @return
     */
    private String CreateOutTradeNoRandom(Long id) {
        String outTradeNo = id.toString();
        Random random = new Random();
        for (int i = outTradeNo.length(); i <= 14; i++) {
            // 随机生成 0 到 9 的整数，加入昵称
            int num = random.nextInt(10);
            outTradeNo += num;
        }
        return outTradeNo;
    }
}
